<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Validate;
use app\facade\Redis;
use app\models\{User as Users, Money, Moneylog, Order as Orders, Orderlog, Quotes, Price, Withdraw,Wallet,Gathercoin};
use think\Facade\Config as Configs;


class Order extends Base
{
    public function Index()
    {
        $ModelFun = new Quotes();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        if (!empty($data['coin'])) {
            $list = $list->where('coin', $data['coin']);
        }
        if (!empty($data['mart'])) {
            $list = $list->where('mart', $data['mart']);
        }
        if (!empty($data['istrans'])) {
            $list = $list->where('istrans', $data['istrans']);
        }
        if (!empty($data['ishow'])) {
            $list = $list->where('ishow', $data['ishow']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['cointext'] = Configs::get('config.coins.' . $user['coin']);
            $user['marttext'] = Configs::get('config.martcoins.' . $user['mart']);
            return $user;
        });
        $coin = Configs::get('config.coins');
        $mart = Configs::get('config.martcoins');
        return view('', ['list' => $list, 'coin' => $coin, 'mart' => $mart]);
    }

    public function quotes_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'coin' => 'require',
                'mart' => 'require',
            ], [
                'coin.require' => '交易币种不能为空',
                'mart.require' => '交易币种市场不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['coin'] == $data['mart']) {
                return json(['status' => 1, 'data' => [], 'msg' => '交易币种与市场币种不能一样']);
            }
            $Quotes = (new Quotes())->where(['coin' => $data['coin'], 'mart' => $data['mart']])->find();
            if (!empty($Quotes)) {
                if (!empty($data['id']) && $data['id'] != $Quotes['id']) {
                    return json(['status' => 1, 'data' => [], 'msg' => '币种类型已存在']);
                }
                if (empty($data['id'])) {
                    return json(['status' => 1, 'data' => [], 'msg' => '币种类型已存在']);
                }
            }
            if (!empty($data['id'])) {
                $result =  (new Quotes())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $result =  (new Quotes())->allowfield(true)->save($data);
            }
            if ($result) {
                return json(['status' => 0, 'msg' => '操作成功']);
            } else {
                return json(['status' => 1, 'msg' => '操作失败']);
            }
        } else {
            $id = $this->request->get('id');
            $row = (new Quotes())->where('id', $id)->find();
            $coin = Configs::get('config.coins');
            $mart = Configs::get('config.martcoins');
            return view('', ['row' => $row, 'coin' => $coin, 'mart' => $mart]);
        }
    }

    public function Price()
    {
        $ModelFun = new Price();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        $list = $list->paginate(15, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    public function price_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'price' => 'require|gt:0',
                'dates' => 'require',
            ], [
                'price.require' => '价格不能为空',
                'price.require' => '价格必须大于0',
                'dates.require' => '日期不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['type'] = 1;
            if (!empty($data['id'])) {
                $result =  (new Price())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $result =  (new Price())->allowfield(true)->save($data);
            }
            if ($result) {
                return json(['status' => 0, 'msg' => '操作成功']);
            } else {
                return json(['status' => 1, 'msg' => '操作失败']);
            }
        } else {
            $id = $this->request->get('id');
            $row = (new Price())->where('id', $id)->find();
            return view('', ['row' => $row]);
        }
    }

    public function order()
    {
        $ModelFun = new Orders();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        if (!empty($data['coin'])) {
            $list = $list->where('coin', $data['coin']);
        }
        if (!empty($data['mart'])) {
            $list = $list->where('mart', $data['mart']);
        }
        if (!empty($data['prmoney'])) {
            $list = $list->where('prmoney', $data['prmoney']);
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        if (!empty($data['mobile'])) {
            $id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $id);
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            $user['cointext'] = Configs::get('config.coins.' . $user['coin']);
            $user['marttext'] = Configs::get('config.martcoins.' . $user['mart']);
            return $user;
        });
        $coin = Configs::get('config.coins');
        $mart = Configs::get('config.martcoins');
        return view('', ['list' => $list, 'coin' => $coin, 'mart' => $mart]);
    }

    public function orderstr()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'type' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'id.require' => 'ID必须大于0',
                'type.require' => '状态类型不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $order = (new Orders())->where('id', $data['id'])->find();
            if (empty($order) || $order['status'] != 1) {
                return json(['status' => 1, 'msg' => '订单状态不可修改']);
            }
            $coinnum = 0; //交易币种数量
            $martnum = 0; //市场币种数量
            //计算返回币种数量和类型
            if ($order['type'] == 1) {
                $martnum = $order['commtotal'] - $order['transtotal'];
                $martmoney = (new Money())->where(['user_id' => $order['user_id'], 'type' => $order['mart']])->find();
            } else {
                $coinnum = $order['commnum'] - $order['transnum'];
                $coinmoney = (new Money())->where(['user_id' => $order['user_id'], 'type' => $order['coin']])->find();
            }
            Db::startTrans();
            try {
                (new Orders())->where(['id' => $order['id'], 'status' => 1])->update(['status' => 3]); //取消订单
                if ($coinnum > 0) {
                    (new Money())->where(['user_id' => $order['user_id'], 'type' => $order['coin'], 'money' => $coinmoney['money'],'freezemoney' => $coinmoney['freezemoney']])
                        ->dec('freezemoney', $coinnum)
                        ->inc('money', $coinnum)
                        ->update();
                    (new Moneylog())->insert([
                        'user_id' => $order['user_id'],
                        'befores' => $coinmoney['money'],
                        'money' => $coinnum,
                        'after' => ($coinmoney['money'] + $coinnum),
                        'cointype' => $order['coin'],
                        'type' => 9,
                        'source' => $order['id'],
                        'info' => '挂单取消' . $coinnum . '个(后台操作)'
                    ]);
                }
                if ($martnum > 0) {
                    (new Money())->where(['user_id' => $order['user_id'], 'type' => $order['mart'], 'money' => $martmoney['money'],'freezemoney' => $martmoney['freezemoney']])
                        ->dec('freezemoney', $martnum)
                        ->inc('money', $martnum)
                        ->update();
                    (new Moneylog())->insert([
                        'user_id' => $order['user_id'],
                        'befores' => $martmoney['money'],
                        'money' => $martnum,
                        'after' => ($martmoney['money'] + $martnum),
                        'cointype' => $order['mart'],
                        'type' => 9,
                        'source' => $order['id'],
                        'info' => '挂单取消' . $martnum . '个'
                    ]);
                }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['status' => 1, 'msg' => '取消失败，请重试']);
            }
            return json(['status' => 0, 'msg' => '取消成功']);
        }
    }

    public function orderlog()
    {
        $ModelFun = new Orderlog();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        if (!empty($data['orderid'])) {
            $list = $list->where('orderid|matchid', $data['orderid']);
        }
        if (!empty($data['coin'])) {
            $list = $list->where('coins', $data['coin']);
        }
        if (!empty($data['mart'])) {
            $list = $list->where('mart', $data['mart']);
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        if (!empty($data['mobile'])) {
            $id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('matchuser_id|user_id', $id);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            $user['matchmobile'] = (new Users())->where('id', $user['matchuser_id'])->value('mobile');
            $user['cointext'] = Configs::get('config.coins.' . $user['coins']);
            $user['marttext'] = Configs::get('config.martcoins.' . $user['mart']);
            return $user;
        });
        $coin = Configs::get('config.coins');
        $mart = Configs::get('config.martcoins');
        return view('', ['list' => $list, 'coin' => $coin, 'mart' => $mart]);
    }

    public function withdraw()
    {
        $ModelFun = new Withdraw();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc')->where('type', 1);
        if (!empty($data['coin'])) {
            $list = $list->where('cointype', $data['coin']);
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['address'])) {
            $list = $list->where('address', $data['address']);
        }
        if (!empty($data['mobile'])) {
            $id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $id);
        }
        if (!empty($data['export']) && $data['export'] == 2) {
            $name = '提币报表';
            $header =   ["日期", "姓名", "手机号码",  "提币类型", "转币数量", "状态","备注"];
            $list = $list->select();
            foreach ($list as $lists) {
                $user = (new Users())->where('id', $lists['user_id'])->find();
                $status = '';
                if($lists['status'] == 1){
                    $status = '待审核';
                }
                if ($lists['status'] == 2) {
                    $status = '转币中';
                }
                if ($lists['status'] == 3) {
                    $status = '完成';
                }
                if ($lists['status'] == 4) {
                    $status = '驳回';
                }
                if ($lists['status'] == 5) {
                    $status = '转币失败';
                }
                $datb[] = [
                    $lists['dates'],
                    $user['name'],
                    $user['mobile'],
                    Configs::get('config.coins.' . $lists['cointype']),
                    ($lists['coinnum'] - $lists['handfee']),
                    $status,
                    ''
                ];
            }
            excelExport($name, $header, $datb);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            $user['cointext'] = Configs::get('config.coins.' . $user['cointype']);
            return $user;
        });
        $coin = Configs::get('config.coins');
        return view('', ['list' => $list, 'coin' => $coin]);
    }

    public function withdrawstr()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'type' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'id.gt' => 'ID必须大于0',
                'type.require' => '状态类型不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $order = (new Withdraw())->where('id', $data['id'])->find();
            if (empty($order) || ($order['status'] != 1 && $order['status'] != 5 && $order['status'] != 2)) {
                return json(['status' => 1, 'msg' => '订单状态不可修改']);
            }
            $usermoney = (new Money())->where(['user_id' => $order['user_id'], 'type' => $order['cointype']])->find();
            Db::startTrans();
            try {
                (new Withdraw())->where(['id' => $order['id'], 'status' => $order['status']])->update(['status' => $data['type'],'dates' => date('Y-m-d'),'succtime' => date('Y-m-d H:i:s')]);
                if ($data['type'] == 4) {
                    (new Money())->where(['user_id' => $order['user_id'], 'type' => $order['cointype'], 'money' => $usermoney['money']])
                        ->setInc('money', $order['coinnum']);
                    (new Moneylog())->insert([
                        'user_id' => $order['user_id'],
                        'befores' => $usermoney['money'],
                        'money' => $order['coinnum'],
                        'after' => ($usermoney['money'] + $order['coinnum']),
                        'cointype' => $order['cointype'],
                        'handfee' => 0,
                        'type' => 11,
                        'info' => '提现申请驳回还' . $order['coinnum'] . '个'
                    ]);
                }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['status' => 1, 'msg' => '审核失败，请重试']);
            }
            return json(['status' => 0, 'msg' => '审核成功']);
        }
    }

    public function wallet()
    {
        $ModelFun = new Wallet();
        $data = $this->request->get();
        $list = $ModelFun->order('money desc');
        if (!empty($data['cointype'])) {
            $list = $list->where('type', $data['cointype']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['private'] = substr($user['private'], 5);
            $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            $user['cointext'] = Configs::get('config.coins.' . $user['type']);
            return $user;
        });
        $coin = Configs::get('config.coins');
        return view('', ['list' => $list, 'coin' => $coin]);
    }

    public function walletstr()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'user_id' => 'require|gt:0',
                'type' => 'require',
                'money' => 'require|gt:0',

            ], [
                'user_id.require' => '用户ID不能为空',
                'user_id.gt' => '用户ID必须大于0',
                'type.require' => '提币类型不能为空',
                'money.require' => '扣币数量不能为空',
                'money.gt' => '扣币数量必须大于0',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $Wallet = (new Wallet())->where(['user_id' => $data['user_id'],'type' => $data['type']])->find();
            if (empty($Wallet)) {
                return json(['status' => 1, 'msg' => '订单不存在']);
            }
            if($Wallet['money'] < $data['money']){
                return json(['status' => 1, 'msg' => '钱包内币种数目不足']);
            }
            Db::startTrans();
            try {
                (new Wallet())->where(['user_id' => $data['user_id'],'type' => $data['type']])->setDec('money',$data['money']);
                (new Gathercoin())->insert([
                    'user_id' => $Wallet['user_id'],
                    'cointype' => $Wallet['type'],
                    'num' => $data['money'],
                    'type'=> 3,
                    'status' => 2,
                ]);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                dump($e->getMessage());
                return json(['status' => 1, 'msg' => '扣除失败，请重试']);
            }
            return json(['status' => 0, 'msg' => '扣除成功']);
        }
    }
}
